package org.spring.data.jpa.demo.service;

import org.spring.data.jpa.demo.dao.UserDao;
import org.spring.data.jpa.demo.dto.UserDTO;
import org.spring.data.jpa.demo.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @date 2021/9/6
 * @auther uranus
 */
@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserDao dao;
    @Override
    public UserDTO create(UserDTO userDTO) {
        User user=new User();
        BeanUtils.copyProperties(userDTO,user);
        dao.save(user);
        userDTO.setId(user.getId());
        return userDTO;
    }

    @Override
    public UserDTO update(UserDTO userDTO) {
        User user=new User();
        BeanUtils.copyProperties(userDTO,user);
        dao.save(user);
        return userDTO;
    }

    @Override
    public void delete(String id) {
        dao.deleteById(id);
    }

    @Override
    public UserDTO getById(String id) {
        Optional<User> byId=dao.findById(id);
        if(byId!=null){
            User user=byId.get();
            System.out.println("service:"+user);
            UserDTO dto=user.build(user);
            return dto;
        }else {
            return null;
        }
    }
}
